import { IBreadCrumb } from '@/base-ui/breadcrumb'
import { RouteRecordRaw } from 'vue-router'

// 定义第一个menu
let firstMenu: any = null

// 将用户的menus与自己创建的menus进行对比匹配
export function MenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const Routes: RouteRecordRaw[] = []

  // 1.先加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = []
  //     通过require对象的context()加载文件夹下的文件  是否递归  正则匹配   (webpack的require)
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    //            require()通过文件路径找到文件对象
    const route = require('@/router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  // 2 通过userMenus加载对应的routes
  // 定义递归函数进行路径匹配
  const _recursGetRoute = (Menus: any[]) => {
    for (const menu of Menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => {
          // 因为接口返回的url与我的文件夹名字的路径不同,所以进行切割
          return route.path === menu.url
        })
        if (route) {
          Routes.push(route)
        }
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        _recursGetRoute(menu.children)
      }
    }
  }

  _recursGetRoute(userMenus)

  return Routes
}

// 面包屑的展示
export function pathToBreadCrumbs(userMenus: any[], currentpath: string): any {
  const breadcrumbs: IBreadCrumb[] = []
  pathToMenus(userMenus, currentpath, breadcrumbs)
  return breadcrumbs
}

// 传入路径和menu,通过匹配拿到当前的menu
export function pathToMenus(
  userMenus: any[],
  currentpath: string,
  breadcrumbs?: IBreadCrumb[]
): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findmenu = pathToMenus(menu.children ?? [], currentpath)
      if (findmenu) {
        breadcrumbs?.push({ name: menu.name })
        breadcrumbs?.push({ name: findmenu.name })
        return findmenu
      }
    } else if (menu.type === 2 && menu.url === currentpath) {
      return menu
    }
  }
}
//  权限设置
export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = []
  const _recuresGetpermissions = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recuresGetpermissions(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recuresGetpermissions(userMenus)
  return permissions
}

// 获取menu的叶子节点
export function getMenuLeafKeys(menu: any[]) {
  const leafKeys: number[] = []
  const _recuresLeafKeys = (menu: any[]) => {
    for (const item of menu) {
      if (item.children) {
        _recuresLeafKeys(item.children)
      } else {
        leafKeys.push(item.id)
      }
    }
  }
  _recuresLeafKeys(menu)
  return leafKeys
}

export { firstMenu }
